import java.util.Random;

//实现堵塞队列
public class MyBlockingQueue {
    public int[] num=new int[1000];
    private int size=0;
    private int head=0;
    private int end=0;
    public void put(int val)throws InterruptedException{
        synchronized (this){
            while(size==num.length){
                this.wait();
            }
            num[end]=val;
            end=(end+1)% num.length;
            size++;
            notifyAll();
        }
    }
    public int take()throws InterruptedException{
        int result=0;
        synchronized (this) {
            while (size == 0) {
                this.wait();
            }
            result = num[head];
            head = (head + 1) % num.length;
            size--;
            this.notifyAll();
        }
        return result;
    }
    public synchronized int getSize(){
        return size;
    }
    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue=new MyBlockingQueue();
        Thread customer=new Thread(()->{
           while(true){
               try {
                   int nums= myBlockingQueue.take();
                   System.out.println("消费了"+nums+",目前队列大小为："+myBlockingQueue.getSize());
               }catch (InterruptedException e){
                   e.printStackTrace();
               }
           }
        },"customer");
        customer.start();
        Thread producer=new Thread(()->{
            Random random=new Random();
            while (true){
                try{
                    int nums=random.nextInt(10000);
                    myBlockingQueue.put(nums);
                    System.out.println("生产了"+nums+",目前队列大小为："+myBlockingQueue.getSize());
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        },"producer");
        producer.start();
    }
}

